package com.fhzn.auth.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fhzn.auth.entity.UserRole;
import com.fhzn.auth.web.request.RoleQueryRequest;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

/**
 * @author 老顾
 * @apiNote
 * @since 2023/12/22
 */
public interface UserRoleMapper extends BaseMapper<UserRole> {

    /**
     * 查询角色下用户数量
     *
     * @param roleIdList 角色id列表
     * @return 角色下用户数量
     */
    default List<Map<String, Object>> queryCountOfAssignedUserByRoleIdList(List<Integer> roleIdList) {
        QueryWrapper<UserRole> wrapper = Wrappers.query();
        wrapper.select("count(1) as count", "role_id as roleId")
                .in("role_id", roleIdList)
                .groupBy("role_id");

        return selectMaps(wrapper);
    }

    /**
     * 根据角色id查询用户
     *
     * @param request 角色请求
     * @return 用户分页信息
     */
    default List<UserRole> pageQueryUserListByRoleId(RoleQueryRequest request) {
        LambdaQueryWrapper<UserRole> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserRole::getRoleId, request.getId());
        queryWrapper.orderByAsc(UserRole::getId);
        return selectList(queryWrapper);
    }

    /**
     * 根据用户id和角色id查询用户角色列表
     *
     * @param userIds 用户id列表
     * @param roleId  角色id
     * @return 用户角色列表
     */
    default List<UserRole> queryByUsersAndRole(List<Integer> userIds, Integer roleId) {
        LambdaQueryWrapper<UserRole> wrapper = Wrappers.lambdaQuery();
        wrapper.in(UserRole::getUserId, userIds);
        wrapper.eq(UserRole::getRoleId, roleId);
        return selectList(wrapper);
    }

    /**
     * 批量插入用户角色
     *
     * @param userRoleList 用户角色列表
     */
    @Insert("<script>" +
            "INSERT INTO abstract_auth_user_role (user_id, role_id, creator, modifier) VALUES " +
            "<foreach collection='userRoleList' item='item' separator=','>" +
            "(#{item.userId}, #{item.roleId}, #{item.creator}, #{item.modifier})" +
            "</foreach>" +
            "</script>")
    void batchInsert(@Param("userRoleList") List<UserRole> userRoleList);

    /**
     * 批量删除用户角色
     *
     * @param userRoles 用户角色列表
     */
    @Delete("<script>" +
            "delete from abstract_auth_user_role where (user_id, role_id) in " +
            "<foreach collection='userRoles' open='(' separator=',' close=')' item='roleItem' index='roleIndex'>" +
            "(#{roleItem.userId}, #{roleItem.roleId})" +
            "</foreach>" +
            "</script>")
    void deleteBatchByIds(List<UserRole> userRoles);
}
